package com.chanjiedata.changbs.module.mine;

/**
 * 文件名 : EarningDetailActivity
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/28 20:06
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;

import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseActivity;
import com.chanjiedata.changbs.dialog.SelectMonthDialog;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Recharge;
import com.chanjiedata.changbs.utlis.DateUtil;
import com.chanjiedata.changbs.utlis.StatusBarUtil;
import com.chanjiedata.changbs.utlis.ValidateUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;
import com.ruffian.library.widget.RTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import kale.ui.view.dialog.EasyDialog;

public class EarningDetailActivity extends BaseActivity {

    Unbinder unbinder;
    @BindView(R.id.tv_freeze)
    TextView tvFreeze;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_ti_xian)
    RTextView tvTiXian;
    @BindView(R.id.tv_shouru)
    TextView tvShouru;
    @BindView(R.id.tv_zichu)
    TextView tvZichu;
    @BindView(R.id.tv_zhichu_number)
    TextView tvZhichuNumber;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.tv_search_time)
    TextView tvSearchTime;
    @BindView(R.id.back_tv)
    TextView backTv;
    @BindView(R.id.tv_title)
    TextView tvTitle;


    private List<Fragment> fragmentList;


    private String search_month = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earning_detail);
        unbinder = ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        tvTitle.setText("我的账户");
        search_month = DateUtil.getYear() + "-" + DateUtil.getMonth();
        tvSearchTime.setText(search_month);
        initView();
        initListener();
        loadNumberData();
    }

    private void initListener() {
        backTv.setOnClickListener(view -> finish());
        tvTiXian.setOnClickListener(view -> {
            Intent intent = new Intent(mContext, TiXianActivity.class);
            intent.putExtra("yu_er", tvBalance.getText().toString());
            startActivity(intent);
        });
        tvSearchTime.setOnClickListener(v -> {
            SelectMonthDialog.Builder builder = new SelectMonthDialog.Builder(mContext);
            builder.setOnDialogClickListener((view, month) -> {
                search_month = month;
                tvSearchTime.setText(search_month);
                startFresh();
                loadNumberData();
            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getSupportFragmentManager());
        });

    }

    protected void initView() {
        String[] titles = {"渠道\n收益", "商户\n收益", "激活\n返现", "提现\n记录", "达标\n返现", "其他\n收益"};
        fragmentList = new ArrayList<>();
        fragmentList.add(EaringDetailFragment.NewInstance(1));
        fragmentList.add(EaringDetailFragment.NewInstance(0));
        fragmentList.add(EaringDetailFragment.NewInstance(2));
        fragmentList.add(EaringDetailFragment.NewInstance(3));
        fragmentList.add(EaringDetailFragment.NewInstance(4));
        fragmentList.add(EaringDetailFragment.NewInstance(5));
        viewPager.setOffscreenPageLimit(6);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }

        });
        tabLayout.setupWithViewPager(viewPager);


    }


    // 加载检查是否有绑定银行卡
    private void isBindBankCard() {
        NetworkManager.INSTANCE.post(Apis.my_earnings, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Recharge.My_earnings defaultBean = Recharge.My_earnings.parseFrom(response);
                boolean validate = ValidateUtils.isValidate(defaultBean);
                if (validate) {
                    tvFreeze.setText("已冻结¥" + defaultBean.getFreeze());
                    tvBalance.setText(defaultBean.getAvailable());
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                if (errorCode == 100) {
                    int is_bank = UserHelper.getUser().getIs_bank();
                    if (is_bank == 0) {
                        EasyDialog.Builder builder = EasyDialog.builder(mContext); // 建立builder对象
                        builder.setTitle("提示")
                                .setMessage("请先绑定银行卡")
                                // 设置下方的三个按钮
                                .setPositiveButton("确定", (dialogInterface, i) -> {
                                    startActivity(BankCardActivity.class);
                                    finish();
                                })
                                .setCancelable(false); // 点击空白处可以关闭
                        DialogFragment easyDialog = builder.build();
                        easyDialog.show(getSupportFragmentManager(), "");
                    }
                }
            }
        });
    }


    private void loadNumberData() {
//         加载底部数据
        Recharge.Earnings_detail_info.Builder builder = Recharge.Earnings_detail_info.newBuilder();
        builder.setSearchMonth(search_month);
        NetworkManager.INSTANCE.post(Apis.earnings_detail_info, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Recharge.Earnings_detail_info earningDetailBean = Recharge.Earnings_detail_info.parseFrom(response);
                tvZhichuNumber.setText("¥" + earningDetailBean.getSpending());
                tvShouru.setText("¥" + earningDetailBean.getIncome());

            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    private void startFresh() {
        for (int i = 0; i < fragmentList.size(); i++) {
            ((EaringDetailFragment) fragmentList.get(i)).startReflash(search_month);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isBindBankCard();
    }
}
